package org.ling.xuan.pipeline;

import cn.hutool.core.io.FileUtil;
import com.intellij.openapi.project.Project;
import org.ling.xuan.channel.FileContentCheckChannel;
import org.ling.xuan.channel.FileNameAndPathCheckChannel;
import org.ling.xuan.channel.SvnCheckChannel;
import org.ling.xuan.context.AddPipeLineContext;
import org.ling.xuan.entity.HundSonInfo;
import org.ling.xuan.entity.mo.CommonSetting;
import org.ling.xuan.entity.mo.LocalAdd;
import org.ling.xuan.entity.mo.ProjectSetting;
import org.ling.xuan.rule.FilePathNameCheckRule;
import org.ling.xuan.rule.HundSunVersionCheckRule;
import org.ling.xuan.rule.JavaFileCheckRule;
import org.ling.xuan.rule.SqlContentCheckRule;
import org.ling.xuan.rule.SvnVersionCheckRule;
import org.ling.xuan.util.LxStrUtil;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PipeLineFactory {
    private static final Lock lock = new ReentrantLock();
    private static CheckPipeline<AddPipeLineContext> pipeline;


    public static CheckPipeline<AddPipeLineContext> pipelineInstance() {
        if (pipeline == null) {
            lock.lock();
            try {
                if (pipeline == null) {
                    pipeline = new CheckPipeline<>();
                    FileNameAndPathCheckChannel c = new FileNameAndPathCheckChannel();
                    c.rule(new FilePathNameCheckRule());
                    FileContentCheckChannel fc = new FileContentCheckChannel();
                    fc.rule(new HundSunVersionCheckRule());
                    fc.rule(new SqlContentCheckRule());
                    fc.rule(new JavaFileCheckRule());
                    pipeline.channel(new SvnCheckChannel().rule(new SvnVersionCheckRule()))
                            .channel(fc)
                            .channel(c);
                }
            } finally {
                lock.unlock();
            }
        }
        return pipeline;
    }


    /**
     * 添加时的代码检查策略
     *
     * @param project  项目
     * @param filePath 文件路径
     * @param add      添加
     * @return {@link AddPipeLineContext}
     */
    public static AddPipeLineContext buildContext(Project project, ProjectSetting ps, CommonSetting cs, String filePath, LocalAdd add) {
        AddPipeLineContext context = new AddPipeLineContext(add);
        context.setFilePath(LxStrUtil.unionPath(filePath));
        context.setLocalAdd(add);
        context.setProject(project);
        context.setProjectSetting(ps);
        context.setCommonSetting(cs);
        if (FileUtil.exist(filePath) && filePath.endsWith(".java")) {
            context.setHundSonInfo(new HundSonInfo(filePath, ps.getSystemName(), cs.getAuth()));
        }
        return context;
    }


}
